<template>
  <div :id="id" style="width:100%;height:100%"></div>
</template>

<script setup>
import * as echarts from "echarts";
import { watch, onMounted, onUnmounted } from "vue";

const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  chartData: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(["click"]);

let charts = {};

watch(props.chartData, (newVal, oldVal) => {
  charts.setOption(newVal);
});

onMounted(() => {
  initEcharts();
});

//处理echart的缩放问题
const resizeFunction = () => {
  charts.resize();
};

const initEcharts = () => {
  charts = echarts.init(document.querySelector(`#${props.id}`));

  window.addEventListener("resize", resizeFunction, false);

  charts.on("click", (params) => {
    emit("click", params);
  });

  charts.setOption(props.chartData);
};

onUnmounted(() => {
  window.removeEventListener("resize", resizeFunction);
});
</script>
